
import demo.Chart;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DropMode;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import org.jfree.ui.RefineryUtilities;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Lucas
 */
public class TCC extends javax.swing.JFrame {

    private     BD_Connector        bd;
    private     ResultSet           resultSet;    
    private     Chart               chart;
    private     String              sql;
    private     int                 maxNumRowI = 5;
    private     int                 page = 0;
    private     int                 offset = 0;
    private     int                 row = 0;
    /**
     * Creates new form TCC
     */
    public TCC() {
        initComponents();
        
        try {
            bd = new BD_Connector();
        } catch (SQLException ex) {
            Logger.getLogger(TCC.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        btGrafico = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel3 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        dataDe = new javax.swing.JTextField();
        horaDe = new javax.swing.JTextField();
        horaAte = new javax.swing.JTextField();
        dataAte = new javax.swing.JTextField();
        sensorDe = new javax.swing.JTextField();
        sensorAte = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        cbSelecao = new javax.swing.JComboBox();
        jLabel13 = new javax.swing.JLabel();
        ROWCOUNT = new javax.swing.JLabel();
        jLabel14 = new javax.swing.JLabel();
        maxNumRow = new javax.swing.JTextField();
        jLabel15 = new javax.swing.JLabel();
        jtPagina = new javax.swing.JTextField();
        jbAnterior = new javax.swing.JButton();
        jbProximo = new javax.swing.JButton();
        jbAtualizar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Menu de opções");

        jButton1.setText("Ler log");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        btGrafico.setText("Gráfico");
        btGrafico.setEnabled(false);
        btGrafico.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btGraficoActionPerformed(evt);
            }
        });

        jButton2.setText("Reiniciar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 95, Short.MAX_VALUE)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btGrafico, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btGrafico)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Dia da leitura", "Hora da Leitura", "Sensor", "Situação", "SMS Enviada", "Valor"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jLabel2.setText("Seleção customizada: ");

        jLabel3.setText("Data: ");

        jLabel4.setText("Hora: ");

        dataDe.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                dataDeActionPerformed(evt);
            }
        });

        dataAte.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                dataAteActionPerformed(evt);
            }
        });

        jLabel5.setText("de");

        jLabel6.setText("de");

        jLabel7.setText("até");

        jLabel8.setText("até");

        jLabel9.setText("Sensor: ");

        jLabel10.setText("até");

        jLabel11.setText("de");

        jLabel12.setText("Seleção simplificada: ");

        jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);

        cbSelecao.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "-----", "Última hora", "Hoje", "Desde ontem", "Desde começo da semana" }));
        cbSelecao.setSelectedIndex(2);
        cbSelecao.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbSelecaoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel9)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel11)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(sensorDe, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel10)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(sensorAte, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addGap(18, 18, 18)
                                .addComponent(jLabel6))
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addGap(18, 18, 18)
                                .addComponent(jLabel5)))
                        .addGap(13, 13, 13)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(horaDe, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel8)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(horaAte, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(dataDe, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(dataAte, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 63, Short.MAX_VALUE)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel12)
                    .addComponent(cbSelecao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(dataDe, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel3)
                                .addComponent(dataAte, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel5)
                                .addComponent(jLabel7)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(horaDe, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel8)
                            .addComponent(horaAte, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel6))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel11)
                            .addComponent(jLabel9)
                            .addComponent(sensorDe, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel10)
                            .addComponent(sensorAte, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel12)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cbSelecao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))))
            .addComponent(jSeparator1)
        );

        jLabel13.setText("Quantidade de registros encontrados: ");

        jLabel14.setText("Quantidade máxima de registros por página: ");

        maxNumRow.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                maxNumRowActionPerformed(evt);
            }
        });

        jLabel15.setText("Página: ");

        jtPagina.setEditable(false);
        jtPagina.setText("1");
        jtPagina.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtPaginaActionPerformed(evt);
            }
        });

        jbAnterior.setText("Anterior");
        jbAnterior.setEnabled(false);
        jbAnterior.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbAnteriorActionPerformed(evt);
            }
        });

        jbProximo.setText("Próxima");
        jbProximo.setEnabled(false);
        jbProximo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbProximoActionPerformed(evt);
            }
        });

        jbAtualizar.setText("Atualizar");
        jbAtualizar.setEnabled(false);
        jbAtualizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbAtualizarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel13)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(ROWCOUNT, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel14)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(maxNumRow, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel15)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jtPagina, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jbAtualizar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jbAnterior)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jbProximo)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel13)
                    .addComponent(ROWCOUNT, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel14)
                    .addComponent(maxNumRow, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel15)
                    .addComponent(jtPagina, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbAnterior)
                    .addComponent(jbProximo)
                    .addComponent(jbAtualizar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:       
        row = 0;
        try {
            sql = "SELECT COUNT(1) AS 'NUMROW' FROM LOG " +
                   condicaoWhere();
            System.out.println(sql);
            resultSet = bd.consultaBase( sql );
            
            if(resultSet.next()){
                System.out.println("Quantidade de registros encontrados: " + resultSet.getInt("NUMROW"));
                ROWCOUNT.setText(String.valueOf(resultSet.getInt("NUMROW")));
            }
            
            if(maxNumRow.getText().isEmpty()){
                maxNumRowI = 100;
            } else if(Integer.parseInt(maxNumRow.getText()) > 0 && Integer.parseInt(maxNumRow.getText()) < 1000){
                maxNumRowI = Integer.parseInt(maxNumRow.getText());
            } else {
                maxNumRowI = 1000;
            }
            
            maxNumRow.setText(String.valueOf(maxNumRowI));
            
            page = 1;
            offset = 0;
            
            sql = "SELECT * FROM LOG " +
                    condicaoWhere() +
                    "ORDER BY DIA_LEITURA DESC, HORA_LEITURA DESC, IDSENSOR ";
            System.out.println(sql + "LIMIT " + offset + "," + maxNumRowI);
            resultSet = bd.consultaBase( sql + "LIMIT " + offset + "," + maxNumRowI);
            
            DefaultTableModel tmodel = new DefaultTableModel();
            tmodel = (DefaultTableModel) jTable1.getModel();
            
            while (tmodel.getRowCount() != 0){
                tmodel.removeRow(0);    
            }
            
            while (resultSet.next()) {    
                tmodel.addRow(new Object[row]);   
                
                jTable1.setValueAt(resultSet.getString("DIA_LEITURA"),   row,    0);
                jTable1.setValueAt(resultSet.getString("HORA_LEITURA"),  row,    1);
                jTable1.setValueAt(resultSet.getString("IDSENSOR"),      row,    2);
                jTable1.setValueAt(resultSet.getString("SITUAC"),        row,    3);
                jTable1.setValueAt(resultSet.getString("SMS"),           row,    4);
                jTable1.setValueAt(resultSet.getString("VALOR"),         row++,  5);
            }
            
            btGrafico.setEnabled(true);
            horaDe.setEnabled(false);
            horaAte.setEnabled(false);
            dataDe.setEnabled(false);
            dataAte.setEnabled(false);
            sensorDe.setEnabled(false);
            sensorAte.setEnabled(false);
            cbSelecao.setEnabled(false);
            maxNumRow.setEnabled(false);
            jtPagina.setEditable(true);
            jbAtualizar.setEnabled(true);
            jbProximo.setEnabled(true);
            jbAnterior.setEnabled(true);

        } catch (SQLException ex) {
            Logger.getLogger(TCC.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }//GEN-LAST:event_jButton1ActionPerformed

    private void dataDeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dataDeActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_dataDeActionPerformed

    private void dataAteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dataAteActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_dataAteActionPerformed

    private void btGraficoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btGraficoActionPerformed
        // TODO add your handling code here:
        
            String sql = "SELECT * FROM LOG " +
                    condicaoWhere() +
                    "ORDER BY DIA_LEITURA, HORA_LEITURA, IDSENSOR";
        try {
            resultSet = bd.consultaBase( sql );
        } catch (SQLException ex) {
            Logger.getLogger(TCC.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        chart = new Chart("Análise gráfica.", resultSet);
        chart.pack();
        RefineryUtilities.centerFrameOnScreen(chart);
        chart.setVisible(true);
    }//GEN-LAST:event_btGraficoActionPerformed

    private void cbSelecaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbSelecaoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cbSelecaoActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        
        btGrafico.setEnabled(false);
        horaDe.setEnabled(true);
        horaAte.setEnabled(true);
        dataDe.setEnabled(true);
        dataAte.setEnabled(true);
        sensorDe.setEnabled(true);
        sensorAte.setEnabled(true);
        cbSelecao.setEnabled(true);
        
        if(chart != null){
            chart.setVisible(false);
        }
        ROWCOUNT.setText("");
        maxNumRow.setEnabled(true);        
        
        jtPagina.setEditable(false);
        jbAtualizar.setEnabled(false);
        jbProximo.setEnabled(false);
        jbAnterior.setEnabled(false);

    }//GEN-LAST:event_jButton2ActionPerformed

    private void jtPaginaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtPaginaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jtPaginaActionPerformed

    private void jbAnteriorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAnteriorActionPerformed
        // TODO add your handling code here:
        
        if(Integer.parseInt(jtPagina.getText()) > 1){
            jtPagina.setText(String.valueOf(Integer.parseInt(jtPagina.getText()) - 1));
            atualizaPagina();    
        } else {
            jtPagina.setText("1");
            atualizaPagina();    
        }
        
        
    }//GEN-LAST:event_jbAnteriorActionPerformed

    private void maxNumRowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_maxNumRowActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_maxNumRowActionPerformed
       
    private void jbAtualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAtualizarActionPerformed
        if(Integer.parseInt(jtPagina.getText())>=1){
            atualizaPagina();    
        } else {
            jtPagina.setText("1");
            atualizaPagina();    
        }
    }//GEN-LAST:event_jbAtualizarActionPerformed

    private void jbProximoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbProximoActionPerformed
        // TODO add your handling code here:
        
        if(Integer.parseInt(jtPagina.getText())>=1){
            jtPagina.setText(String.valueOf(Integer.parseInt(jtPagina.getText()) + 1));
            atualizaPagina();    
        } else {
            jtPagina.setText("1");
            atualizaPagina();    
        }
        
    }//GEN-LAST:event_jbProximoActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TCC.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TCC.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TCC.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TCC.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TCC().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel ROWCOUNT;
    private javax.swing.JButton btGrafico;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JComboBox cbSelecao;
    private javax.swing.JTextField dataAte;
    private javax.swing.JTextField dataDe;
    private javax.swing.JTextField horaAte;
    private javax.swing.JTextField horaDe;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton jbAnterior;
    private javax.swing.JButton jbAtualizar;
    private javax.swing.JButton jbProximo;
    private javax.swing.JTextField jtPagina;
    private javax.swing.JTextField maxNumRow;
    private javax.swing.JTextField sensorAte;
    private javax.swing.JTextField sensorDe;
    // End of variables declaration//GEN-END:variables

    private String constroiCondicao(String field, String de, String ate){
        String condicaoCampo = "";
        
        if (de.isEmpty() && 
            ate.isEmpty()) {
            condicaoCampo = "";
        } else {
            condicaoCampo += field + " ";
            if (de.isEmpty()){    
                    condicaoCampo = "";
            } else {
                if (ate.isEmpty()){
                    condicaoCampo += "='" + de + "' ";
                } else {
                    condicaoCampo += "BETWEEN '" + de + "' AND '" + ate + "' ";
                }
            }
        }
        return condicaoCampo;
    }
    
    
    private String condicaoWhere() {
        
        String retorno = "WHERE ";
        String diaLeitura   = constroiCondicao("DIA_LEITURA", dataDe.getText(), dataAte.getText());
        String horaLeitura  = constroiCondicao("HORA_LEITURA", horaDe.getText(), horaAte.getText());  
        String sensor       = constroiCondicao("IDSENSOR", sensorDe.getText(), sensorAte.getText());  
        if (diaLeitura.isEmpty()  &&
            horaLeitura.isEmpty() &&
            sensor.isEmpty()        ) {
            retorno = "";
        }
        
        System.out.println(diaLeitura);
        System.out.println(horaLeitura);
        System.out.println(sensor);
        
        retorno += diaLeitura
                + ((diaLeitura.isEmpty() ||     (horaLeitura.isEmpty() && sensor.isEmpty()  ))?"":"AND ")
                + horaLeitura
                + ((horaLeitura.isEmpty() ||    (sensor.isEmpty()                           ))?"":"AND ")
                + sensor;
        
        
        
        Date date   = new Date();
        String      strDate = "";
        DateFormat  dateFormat;
        dateFormat  = new SimpleDateFormat("yyyyMMdd");
        
        Calendar calendar = new GregorianCalendar();
        String year     =   String.format   ( "%04d", calendar.get(Calendar.YEAR));
        String month    =   String.format   ( "%02d", calendar.get(Calendar.MONTH) + 1);
        String day      =   String.format   ( "%02d", calendar.get(Calendar.DAY_OF_MONTH));
        String hour     =   String.format   ( "%02d", calendar.get(Calendar.HOUR_OF_DAY));
        String minute   =   String.format   ( "%02d", calendar.get(Calendar.MINUTE) );
        String second   =   String.format   ( "%02d", calendar.get(Calendar.SECOND) );
        
        if(calendar.get(Calendar.MONTH) + 1 == 13 ){
            month = "01";
        }
            
        System.out.println(year + month + day + hour + minute + second);
        switch(cbSelecao.getSelectedIndex()){
            case 0:
                break;
            case 1: // última hora
                hour     =   String.format   ( "%02d", calendar.get(Calendar.HOUR_OF_DAY) - 1);
                retorno     = "WHERE DIA_LEITURA = '"       +
                                year + month    + day       + "' AND HORA_LEITURA >= '" +
                                hour + minute   + second    + "' ";
                break;
            case 2: // no dia
                retorno     = "WHERE DIA_LEITURA = '"       +
                                year + month    + day       + "' ";
                break;
            case 3: // desde ontem
                day      =   String.format   ( "%02d", calendar.get(Calendar.DAY_OF_MONTH) - 1);
                retorno     = "WHERE DIA_LEITURA >= '"       +
                                year + month    + day       + "' ";
                break;
            case 4: // na semana
                if(calendar.get(Calendar.DAY_OF_MONTH) >= 7) {
                    day     =   String.format   ( "%02d", calendar.get(Calendar.DAY_OF_MONTH) - calendar.get(Calendar.DAY_OF_WEEK));
                } else {
                    day     = "00";
                }
                retorno     = "WHERE DIA_LEITURA >= '"       +
                                year + month    + day       + "' ";
                break;
            default:
                retorno = ""; // sempre
                break;
        }
        
        
        return retorno;
    }

    private void atualizaPagina() {
        try {
            // TODO add your handling code here:
            
                page = Integer.parseInt(jtPagina.getText());
                offset = (page-1)*maxNumRowI;   
                
                System.out.println(sql + "LIMIT " + offset + "," + maxNumRowI);
                resultSet = bd.consultaBase( sql + "LIMIT " + offset + "," + maxNumRowI);
                DefaultTableModel tmodel = new DefaultTableModel();
                tmodel = (DefaultTableModel) jTable1.getModel();
                
                while (tmodel.getRowCount() != 0){
                    tmodel.removeRow(0);    
                }
                
                row = 0;
                while (resultSet.next()) {    
                    tmodel.addRow(new Object[row]);   
                    jTable1.setValueAt(resultSet.getString("DIA_LEITURA"),   row,    0);
                    jTable1.setValueAt(resultSet.getString("HORA_LEITURA"),  row,    1);
                    jTable1.setValueAt(resultSet.getString("IDSENSOR"),      row,    2);
                    jTable1.setValueAt(resultSet.getString("SITUAC"),        row,    3);
                    jTable1.setValueAt(resultSet.getString("SMS"),           row,    4);
                    jTable1.setValueAt(resultSet.getString("VALOR"),         row++,  5);
                }
        } catch (SQLException ex) {
            Logger.getLogger(TCC.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
